package com.drore.cloud.controller;

import com.drore.cloud.constant.LocalConstant;
import com.drore.cloud.domain.sys.RestMessage;
import com.drore.cloud.exception.ApiException;
import com.drore.cloud.jdbc.MultiDS;
import com.drore.cloud.sdkjdbc.core.JdbcRunner;
import com.drore.cloud.sdkjdbc.model.Pagination;
import com.drore.cloud.utils.*;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.*;

/***
 * 浙江卓锐科技股份有限公司 版权所有@Copyright 2016
 * 说明
 * 项目名称
 * @since:cloud-ims 1.0
 * @author <a href="mailto:baoec@drore.com">baoec@drore.com </a> 
 * 2018/06/20 13:12
 */
@Api("表、字段资源模块")
@RequestMapping(value = "/dbm/resource")
@RestController
public class ResourceCtl {
    @Autowired
    private JdbcRunner run;

    @Autowired
    private MultiDS mult;

    @ApiOperation("资源新增/保存")
    @RequestMapping(value = "/save" ,method = {RequestMethod.POST, RequestMethod.GET})
    public RestMessage save(String resource_name, String submit_data) {
        Map<String, Object> sys_user_info = (Map<String, Object>) ThreadLocalHolder.getCurrentUser();
        String data_source_id = Objects.toString(sys_user_info.get("data_source_id"));
        RestMessage rm=new RestMessage();
        Gson gson = GsonUtil.create();
        Map<String,Object> map = gson.fromJson(submit_data, Map.class);
        if(map.get("file")!=null){
            map.remove("file");
        }
        String insert=null;
        map= MapClearUtil.clear(map);
        if(map.get("id")==null){
            map.put("r_status","wait_issue");
            map.put("data_id",data_source_id);
            insert=run.insert(resource_name,map);
            //表新增成功后  添加系统默认字段
            List<Map<String,Object>> sysfields = Lists.newArrayList();
            HashMap<String, Object> idmap = Maps.newHashMap();
            idmap.put("rd_cn_name","id");
            idmap.put("rd_name","id");
            idmap.put("rd_length",0);
            idmap.put("is_pk","true");
            idmap.put("fk_resource_id",insert);
            idmap.put("field_type","TEXT");
            idmap.put("is_system","true");
            idmap.put("rd_description","system_id");
            idmap.put("data_id",data_source_id);
            HashMap<String, Object> createmap = Maps.newHashMap();
            createmap.put("rd_cn_name","create_time");
            createmap.put("rd_name","create_time");
            createmap.put("rd_length",0);
            createmap.put("is_pk","false");
            createmap.put("fk_resource_id",insert);
            createmap.put("field_type","TEXT");
            createmap.put("is_system","true");
            createmap.put("rd_description","system_create_time");
            createmap.put("data_id",data_source_id);
            sysfields.add(idmap);
            sysfields.add(createmap);
            try {
                run.insertBatch("resource_detail",sysfields);
            } catch (SQLException e) {
                throw new ApiException(e.getLocalizedMessage());
            }
        }else {
            insert=run.update(resource_name,map);
        }
        rm.setData(insert);
        return rm;
    }

    @ApiOperation("资源列表接口")
    @PostMapping("/list")
    public Pagination<Map> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10")Integer limit, String content) {
        Map<String, Object> sys_user_info = (Map<String, Object>) ThreadLocalHolder.getCurrentUser();
        String data_source_id = Objects.toString(sys_user_info.get("data_source_id"));

        StringBuffer sql;
        if(StringUtils.isNotBlank(content)){
             sql=new StringBuffer("select * from resources_info where r_cn_name like '%")
                     .append(content).append("%' or r_description like '%")
                     .append(content).append("%' or r_name like '%")
                     .append(content).append("%'").append(" and data_id='"+data_source_id+"'");
        }else {
            sql=new StringBuffer("select * from resources_info").append(" where data_id='"+data_source_id+"'");
        }
        Pagination<Map> pagination = run.queryBySql(sql.toString(), page, limit);

        return pagination;
    }

    @ApiOperation("字段新增/保存")
    @RequestMapping(value = "/detail/save" ,method = {RequestMethod.POST, RequestMethod.GET})
    public RestMessage detail_save( String submit_data) {
        Map<String, Object> sys_user_info = (Map<String, Object>) ThreadLocalHolder.getCurrentUser();
        String data_source_id = Objects.toString(sys_user_info.get("data_source_id"));
        RestMessage rm=new RestMessage();
        Gson gson = GsonUtil.create();
        Map<String,Object> map = gson.fromJson(submit_data, Map.class);
        if(map.get("file")!=null){
            map.remove("file");
        }
        String insert=null;
        map= MapClearUtil.clear(map);
        if(map.get("id")==null){
            map.put("is_system","false");
            map.put("data_id",data_source_id);
            insert=run.insert("resource_detail",map);
        }else {
            insert=run.update("resource_detail",map);
        }
        rm.setData(insert);
        return rm;
    }

    @ApiOperation("资源明细列表接口")
    @PostMapping("/resources_detail_list")
    public Pagination<Map> resources_detail_list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10")Integer limit, String content,String fk_resource_id) {
        Map<String, Object> sys_user_info = (Map<String, Object>) ThreadLocalHolder.getCurrentUser();
        String data_source_id = Objects.toString(sys_user_info.get("data_source_id"));
        StringBuffer sql;
        if(StringUtils.isNotBlank(content)){
            sql=new StringBuffer("select * from resource_detail where (rd_cn_name like '%")
                    .append(content).append("%' or rd_description like '%")
                    .append(content).append("%' or rd_name like '%")
                    .append(content).append("%')").append(" and fk_resource_id='"+fk_resource_id+"'").append(" and data_id='"+data_source_id+"'")
            .append(" order by create_time desc ");
        }else {
            sql=new StringBuffer("select * from resource_detail where fk_resource_id='"+fk_resource_id+"'"+" and data_id='"+data_source_id+"'");
            sql.append(" order by create_time desc ");
        }
        Pagination<Map> pagination = run.queryBySql(sql.toString(), page, limit);

        return pagination;
    }


    @ApiOperation("导出所有表资源")
    @GetMapping("/exprot")
    public void exprot( HttpServletResponse response) throws Exception {
        Map<String, Object> sys_user_info = (Map<String, Object>) ThreadLocalHolder.getCurrentUser();
        String data_id = Objects.toString(sys_user_info.get("data_source_id"));
        String head="{\"中文名称\":\"r_cn_name\",\"英文名称\":\"r_name\",\"资源描述\":\"r_description\",\"状态\":\"r_status\"}";
        String headDetail="{\"中文名称\":\"rd_cn_name\",\"英文名称\":\"rd_name\",\"资源描述\":\"rd_description\",\"数据类型\":\"field_type\",\"长度\":\"rd_length\",\"是否主键\":\"is_pk\"}";
        //表头
        LinkedHashMap linked = GsonUtil.create().fromJson(head, LinkedHashMap.class);
        LinkedHashMap linked2 = GsonUtil.create().fromJson(headDetail, LinkedHashMap.class);
        //获取所有表资源信息
        Pagination<HashMap<String,Object>> resources_info = run.queryListByExample("resources_info", ImmutableMap.of("data_id",data_id),1,1000);
        //todo 获取所有表结构信息
        StringBuffer resourceids=new StringBuffer();
        int i=0;
        for (Map map : resources_info.getData()) {
            resourceids.append(i==0?"":",").append("'").append(Objects.toString(map.get("id"))).append("'");
            i++;
        }
        Pagination redis_list_structure = run.queryBySql("select * from redis_list_structure where resource_id in ("+resourceids.toString()+")",1,1000);
        System.out.println(redis_list_structure);
        //具体导出
        ExportExcelUtil.ExportResource(linked,linked2,resources_info.getData(),redis_list_structure.getData(),response);
    }

    @ApiOperation("导入表资源")
    @PostMapping("/upload")
    public RestMessage upload(@RequestParam(value="file")MultipartFile file) throws Exception {
        Map<String, Object> sys_user_info = (Map<String, Object>) ThreadLocalHolder.getCurrentUser();
        String data_id = Objects.toString(sys_user_info.get("data_source_id"));
        RestMessage rm=new RestMessage();
        //设置excel 表头字段
        LinkedHashMap<String, String> head = new LinkedHashMap();
        head.put("r_cn_name","中文名称");
        head.put("r_name","英文名称");
        head.put("r_description","资源描述");
        head.put("r_status","状态");
        LinkedHashMap<String, String> headDetail = new LinkedHashMap();
        headDetail.put("rd_cn_name","中文名称");
        headDetail.put("rd_name","英文名称");
        headDetail.put("rd_description","资源描述");
        headDetail.put("field_type","数据类型");
        headDetail.put("rd_length","长度");
        headDetail.put("is_pk","是否主键");
        String filename = file.getOriginalFilename();
        //读取第一个sheet 的所有内容  优先解析(如果有表已经存在 过滤也好跳出也好 都可以)
        List<Map> lists = ImportExcelUtil.getListByIndexExcel(file.getInputStream(), filename,head,0,0,1,0);
        List<Map> resources_insert=new ArrayList<>();
        StringBuffer resource_names=new StringBuffer();
        int i=0;
        for (Map resource : lists) {
            //todo 处理表
            HashMap<Object, Object> resources_info = Maps.newHashMap();
            resources_info.put("r_cn_name",resource.get("r_cn_name"));
            resources_info.put("r_name",resource.get("r_name"));
            resources_info.put("r_description",resource.get("r_description"));
            resources_info.put("r_status","wait_issue");
            resources_info.put("data_id",data_id);
            resources_insert.add(resources_info);
            resource_names.append(i==0?"":",").append("'").append(resource.get("r_name")).append("'");
            i++;
        }
        //TODO 优先采取 终止导入手段    （1已经存在终止导入2可以选择过滤掉）
        Pagination<Map> mapPagination = run.queryBySql("select * from resources_info where data_id='"+data_id+"' and r_name in (" + resource_names.toString() + ")", 1, 1000);
        if(mapPagination.getCount()>0){
            throw new ApiException("导入冲突，请剔除重复资源后再导入");
        }
        //todo 进行具体的 写入数据库操作
        if(resources_insert.size()>0){

            String insert_success_ids = run.insertBatch("resources_info", resources_insert);
            //对返回结果进行处理
            String[] split = insert_success_ids.split(",");
            if(split.length>0){
                int j=0;
                for (Map map : lists) {
                    map.put("fk_resource_id",split[j]);
                    j++;
                }
            }
        }
        //读取第二个开始 的 sheet 的所有内容
        for (Map map : lists) {
            String r_name = Objects.toString(map.get("r_name"));
            List<Map> details = ImportExcelUtil.getListByNameExcel(file.getInputStream(), filename,headDetail,r_name,0,1,0);
            map.put(r_name,details);
        }
        //todo 将得到的结果 进行逻辑处理

        List<Map> resources_detail_insert=new ArrayList<>();
        for (Map<String, Object> resource : lists) {
            List<Map> resources_details = (List) resource.get(resource.get("r_name"));
            String fk_resource_id = (String) resource.get("fk_resource_id");
            for (Map Detail : resources_details) {
                //todo 处理表中 字段
                HashMap<Object, Object> resources_detail = Maps.newHashMap();
                resources_detail.put("rd_cn_name",Detail.get("rd_cn_name"));
                resources_detail.put("rd_name",Detail.get("rd_name"));
                resources_detail.put("rd_description",Detail.get("rd_description"));
                resources_detail.put("field_type",Detail.get("field_type"));
                resources_detail.put("rd_length",Detail.get("rd_length"));
                resources_detail.put("is_pk",Detail.get("is_pk"));
                resources_detail.put("fk_resource_id",fk_resource_id);//所属资源id
                String rd_name = Objects.toString(Detail.get("rd_name"));
                resources_detail.put("is_system",rd_name.equals("id")||rd_name.equals("create_time")?"true":"false");
                resources_detail.put("data_id",data_id);
                resources_detail_insert.add(resources_detail);
            }
        }
        if(resources_detail_insert.size()>0){
            run.insertBatch("resource_detail", resources_detail_insert);
        }
        rm.setMessage("上传成功");
        return rm;
    }

}
